17. Exercise: Add a Filter

L8 33 Adding A Filter HS-SC

Erratum

At timestamp 01:25 onwards in the video above, in OverviewViewModel.kt file, use the updated definition of the getMarsRealEstateProperties() function as mentioned in the instructions below. Alternatively, you can check out the relevant branch of the Git repo.

Now it's your turn to complete this exercise yourself! If you want to start at this step, you can download this exercise from: Step.08-Exercise-Adding-a-Filter. You will find plenty of //TODO comments to help you complete things.

  1. In MarsApiService, create a MarsApiFilter enum that defines constants to match the query values our web service expects:
enum class MarsApiFilter(val value: String) { SHOW_RENT("rent"), SHOW_BUY("buy"), SHOW_ALL("all") }



  1. Add a @Query("filter") parameter to getProperties() so we can filter properties based on the MarsApiFilter enum values:
fun getProperties(@Query("filter") type: String): 



  1. In OverviewViewModel, add a MarsApiFilter parameter to getMarsRealEstateProperties():
 private fun getMarsRealEstateProperties(filter: MarsApiFilter) {


  1. Pass the filter.value to retrofitService.getProperties():
_properties.value = MarsApi.retrofitService.getProperties(filter.value)


  1. In the init block, pass MarsApiFilter.SHOW_ALL as the default parameter to getMarsRealEstateProperties():
getMarsRealEstateProperties(MarsApiFilter.SHOW_ALL)


  1. Now create an updateFilter() method to requery the data by calling getMarsRealEstateProperties with the new filter:
fun updateFilter(filter: MarsApiFilter) {
       getMarsRealEstateProperties(filter)
}


  1. In OverviewFragment, we need to provide a menu option so the user can change the filter. Override onOptionsItemSelected() and pass the selected filter viewModel.updateFilter:

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        viewModel.updateFilter(
            when (item.itemId) {
                R.id.show_rent_menu -> MarsApiFilter.SHOW_RENT
                R.id.show_buy_menu -> MarsApiFilter.SHOW_BUY
                else -> MarsApiFilter.SHOW_ALL
            }
        )
        return true
    }    


  2. Run the app, use the new menu option to change the filter, and start searching for your new dream home on Mars!

If you get stuck, go back and watch the video again. Once you’re done, you can check your solution against the solution we’ve provided here: Step.08-Solution-Adding-a-Filter, or using this git diff.

Task Description:

Complete the tasks below to filter your real estate listings results.

Task List:

Task Feedback:

Great job!

Reference documentation